<?php
/**
 * Created by 2019/4/26 0026
 * Effect: XinYunSaiManSaiMa.php
 * Author: 品花
 * Date: 2019/4/26 0026
 * Time: 上午 10:17
 */

namespace App\WebSocket;

use App\Consts\RedisKey;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\RedisPool\Redis;
use EasySwoole\Socket\AbstractInterface\Controller;

/**
 * Class IM Base
 *
 * 此类是默认的 websocket 消息解析后访问的 控制器
 *
 * @package App\WebSocket
 */
class Base extends Controller
{

    /** 返回数据
     * @param $code 状态码
     * @param array $data 数据
     * @return string
     */
     public function returnData($code,$data=[]){

        $data = json_encode([
            'code'=>$code,
            'msg'=> \App\Consts\ErrorCode::ERROR_CODE_AND_ERORR_MSG[$code],
            'data'=> (object)$data
        ]);

        $this->response()->setMessage($data);

    }


    /**
     * 获取用户ID
     * @return mixed
     * @author 品花
     * @date 2019/11/28 0028 下午 1:20
     */
    public function getUid(){

        $fd = $this->caller()->getClient()->getFd();

        $uid = Redis::defer()->hGet(RedisKey::WS_USER_FD_HASH_LIST,$fd);

        return $uid;

    }

    /**
     * 给用户推送消息
     * @param $fd
     * @param $data
     * @author 品花
     * @date 2019/11/28 0028 下午 2:33
     */
    public function push($fd,$code,$data){
        $data = json_encode([
            'code'=>$code,
            'msg'=> \App\Consts\ErrorCode::ERROR_CODE_AND_ERORR_MSG[$code],
            'data'=>$data
        ]);
        $server = ServerManager::getInstance()->getSwooleServer();
        $server->push($fd,$data);
    }


    /**
     * 心跳检测 +防沉迷检测
     * @author 品花
     * @date 2019/10/23 0023 上午 11:13
     */
    public function heartBeat(){


        $this->returnData(10000);
    }







}